<template>
  <div class="admin-management">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="管理员名">
            <el-input v-model="searchForm.username" placeholder="请输入管理员名" clearable />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item label="角色">
            <el-select 
              v-model="searchForm.role" 
              placeholder="请选择角色" 
              clearable
              class="role-select"
            >
              <el-option 
                v-for="role in roleList" 
                :key="role.id" 
                :value="role.id" 
                :label="role.name"
              >
                <template #default>
                  <el-popover
                    placement="right"
                    :width="300"
                    trigger="hover"
                    :content="role.description"
                    popper-class="role-popover"
                  >
                    <template #reference>
                      <div class="role-option">
                        <el-tag 
                          :type="getRoleTagType(role.id).type" 
                          :effect="getRoleTagType(role.id).effect" 
                          size="small"
                        >
                          {{ role.name }}
                        </el-tag>
                      </div>
                    </template>
                  </el-popover>
                </template>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              class="status-select"
            >
              <el-option :value="0" label="启用">
                <template #default>
                  <div class="status-option">
                    <el-tag type="success" effect="plain" size="small">启用</el-tag>
                  </div>
                </template>
              </el-option>
              <el-option :value="1" label="禁用">
                <template #default>
                  <div class="status-option">
                    <el-tag type="danger" effect="plain" size="small">禁用</el-tag>
                  </div>
                </template>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="operation-box">
        <el-button type="primary" @click="handleAdd">新增管理员</el-button>
      </div>

      <!-- 管理员列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" fixed="left" />
        <el-table-column prop="username" label="管理员名称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="role" label="角色" min-width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              :width="300"
              trigger="hover"
              :content="getRoleDescription(scope.row.role)"
              popper-class="role-popover"
            >
              <template #reference>
                <el-tag 
                  :type="getRoleTagType(scope.row.role).type" 
                  :effect="getRoleTagType(scope.row.role).effect"
                >
                  {{ scope.row.roleName || getRoleName(scope.row.role) }}
                </el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'" effect="plain">
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 0 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >
              {{ scope.row.status === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑管理员' : '新增管理员'"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        class="edit-form"
      >
        <el-form-item label="管理员名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入管理员名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select 
            v-model="editForm.role" 
            placeholder="请选择角色" 
            class="edit-select"
            popper-class="role-select-dropdown"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            >
              <template #default>
                <el-popover
                  placement="right"
                  :width="300"
                  trigger="hover"
                  :content="role.description"
                  popper-class="role-popover"
                >
                  <template #reference>
                    <div class="role-option">
                      <el-tag 
                        :type="getRoleTagType(role.id).type" 
                        :effect="getRoleTagType(role.id).effect" 
                        size="small"
                      >
                        {{ role.name }}
                      </el-tag>
                      <span class="role-description">{{ role.description }}</span>
                    </div>
                  </template>
                </el-popover>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!editForm.id" label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="!editForm.id" label="确认密码" prop="confirmPassword">
          <el-input
            v-model="editForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveAdmin">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminList, getRoleList, updateAdmin, updateAdminStatus, createAdmin, getAdminDeleteVerifyCode, deleteAdmin } from '@/api/admin'

// 角色标签类型映射
const roleTagTypes = {
  // 当前使用的角色样式
  1: { type: 'danger', effect: 'dark' },      // SuperAdmin - 深红色
  2: { type: 'success', effect: 'dark' },     // ContentAdmin - 深绿色
  3: { type: 'warning', effect: 'dark' },     // UserAdmin - 深黄色
  4: { type: 'primary', effect: 'light' },    // RecommendationAdmin - 超浅蓝色
  5: { type: 'info', effect: 'dark' },        // BorrowingAdmin - 深灰色
  6: { type: 'success', effect: 'light' },    // StatisticsAnalyst - 超浅绿色
  7: { type: 'primary', effect: 'dark' },     // adminUser - 深蓝色

  // 预留的角色样式
  8: { type: 'warning', effect: 'light' },    // 超浅黄色
  9: { type: 'danger', effect: 'light' },     // 超浅红色
  10: { type: 'info', effect: 'light' },      // 超浅灰色
  11: { type: 'warning', effect: 'plain' },   // 浅黄色
  12: { type: 'danger', effect: 'plain' },    // 浅红色
  13: { type: 'primary', effect: 'plain' },   // 浅蓝色
  14: { type: 'success', effect: 'plain' },   // 浅绿色
  15: { type: 'info', effect: 'plain' }       // 浅灰色
}

// 搜索表单
const searchForm = ref({
  username: '',
  email: '',
  role: '',
  status: ''
})

// 表格数据示例
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 初始化空的角色列表
const roleList = ref([])

// 格式化时间
const formatDateTime = (time) => {
  if (!time) return '-'
  // 处理后端返回的时间格式 "Tue Nov 26 21:28:47 CST 2024"
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 搜索
const onSubmit = () => {
  currentPage.value = 1
  fetchAdminList()
}

// 重置表单并重新搜索
const resetForm = () => {
  searchForm.value = {
    username: '',
    email: '',
    role: '',
    status: ''
  }
  currentPage.value = 1
  fetchAdminList()
}

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: '',
  username: '',
  email: '',
  role: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (editForm.value.confirmPassword !== '') {
      editFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== editForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const editRules = {
  username: [
    { required: true, message: '请输入管理员名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.value = {
    id: '',
    username: '',
    email: '',
    role: '',
    password: '',
    confirmPassword: ''
  }
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 打开编辑对话框
const handleEdit = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员账户不能被修改')
    return
  }
  editForm.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.role,
    password: '',
    confirmPassword: ''
  }
  editDialogVisible.value = true
}

// 打开新增对话框
const handleAdd = () => {
  resetEditForm()
  editDialogVisible.value = true
}

// 保存管理员信息
const handleSaveAdmin = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构造请求参数
        const params = {
          username: editForm.value.username,
          email: editForm.value.email,
          role: editForm.value.role,
          status: 0  // 默认启用状态
        }

        // 如果是新增,需要添加密码参数
        if (!editForm.value.id) {
          params.password = editForm.value.password
          // 调用新增接口
          const res = await createAdmin(params)
          if (res.code === 0) {
            ElMessage.success('新增成功')
            editDialogVisible.value = false
            fetchAdminList() // 刷新列表
          } else {
            ElMessage.error(res.msg || '新增失败')
          }
        } else {
          // 编辑模式
          params.id = editForm.value.id
          const res = await updateAdmin(params)
          if (res.code === 0) {
            ElMessage.success('修改成功')
            editDialogVisible.value = false
            fetchAdminList() // 刷新列表
          } else {
            ElMessage.error(res.msg || '修改失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 删除管理员
const handleDelete = async (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员账户不能被删除')
    return
  }

  try {
    // 先获取验证码
    const verifyRes = await getAdminDeleteVerifyCode(row.id)
    if (verifyRes.code !== 0) {
      ElMessage.error(verifyRes.msg || '获取验证码失败')
      return
    }

    // 弹出确认对话框,要求输入验证码
    const { value: verifyCode } = await ElMessageBox.prompt(
      '请输入验证码以确认删除操作',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[A-Za-z0-9]{6}$/,
        inputErrorMessage: '验证码格式不正确',
        type: 'warning'
      }
    )

    if (verifyCode) {
      // 调用删除接口
      const res = await deleteAdmin(row.id, verifyCode)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        fetchAdminList() // 刷新列表
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAdminList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAdminList()
}

// 修改状态变更处理函数
const handleStatusChange = async (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('超级管理员账户不能被修改')
    return
  }
  const action = row.status === 0 ? '禁用' : '启用'
  const newStatus = row.status === 0 ? 1 : 0

  try {
    await ElMessageBox.confirm(
      `确定要${action}该管理员账户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: row.status === 0 ? 'warning' : 'info',
      }
    )

    // 调用修改状态接口
    const params = {
      id: row.id,
      status: newStatus
    }
    const res = await updateAdminStatus(params)
    
    if (res.code === 0) {
      ElMessage.success(`${action}成功`)
      // 刷新列表
      fetchAdminList()
    } else {
      ElMessage.error(res.msg || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态修改失败:', error)
      ElMessage.error(`${action}失败`)
    } else {
      ElMessage.info('已取消操作')
    }
  }
}

// 获取角色数据
const fetchRoleList = async () => {
  try {
    const res = await getRoleList()
    if (res.code === 0) {
      // 为每个角色添加前端显示所需的type属性
      roleList.value = res.data.map(role => ({
        id: role.roleId,
        name: role.roleName,
        description: role.description,
        ...roleTagTypes[role.roleId]
      }))
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取管理员列表
const fetchAdminList = async () => {
  try {
    const params = {
      page: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
      username: searchForm.value.username,
      email: searchForm.value.email,
      role: searchForm.value.role ? searchForm.value.role.toString() : '',
      status: searchForm.value.status ? searchForm.value.status.toString() : ''
    }
    
    const res = await getAdminList(params)
    if (res.code === 0) {
      tableData.value = res.data.results.map(item => ({
        ...item,
        createTime: item.creationDate,
        lastLoginTime: item.lastLogin
      }))
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchRoleList()
  fetchAdminList()
})

// 角色映射函数
const getRoleName = (role) => {
  const foundRole = roleList.value.find(item => item.id === role)
  return foundRole ? foundRole.name : '未知角色'
}

// 角色标签类型映射函数
const getRoleTagType = (role) => {
  return roleTagTypes[role] || { type: 'info', effect: 'plain' } // 未知角色使用浅灰色
}

// 添加角色描述获取函数
const getRoleDescription = (role) => {
  const foundRole = roleList.value.find(item => item.id === role)
  return foundRole ? foundRole.description : '暂无描述'
}
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.operation-box {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-select,
.status-select {
  width: 160px;
}

.role-option,
.status-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.role-description {
  color: #666;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.el-button + .el-button {
  margin-left: 8px;
}

:deep(.role-popover) {
  font-size: 14px;
  line-height: 1.5;
  padding: 12px;
  max-width: 300px;
  word-break: break-word;
}

.edit-form {
  padding: 20px;
}

.edit-form :deep(.el-form-item) {
  margin-bottom: 22px;
  display: flex;
  align-items: flex-start;
}

.edit-form :deep(.el-form-item__label) {
  width: 100px;
  text-align: right;
  padding-right: 12px;
  line-height: 32px;
}

.edit-form :deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
}

.edit-select {
  width: 100%;
}

:deep(.role-select-dropdown .el-select-dropdown__item) {
  height: auto;
  padding: 8px 12px;
  line-height: 1.5;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}

/* 搜索表单对齐 */
.demo-form-inline :deep(.el-form-item) {
  margin-bottom: 18px;
  margin-right: 18px;
}

.demo-form-inline :deep(.el-form-item__label) {
  width: 70px;
  text-align: right;
}
</style> 